package imageUtility;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageIntensityDescriptor implements IImageDescriptor {

	private final int mask = 0xff;
	private final int N;
	private final int rank;

	public ImageIntensityDescriptor(int histogramLength) {
		N = histogramLength;
		rank = mask/N;
	}
	
	@Override
	public double[] getImageDescriptors(String imgSrc) {
		int width;
		int height;
		double[] histogram = new double[N];
		BufferedImage bi = null;
		try {
			bi = ImageIO.read( new File( imgSrc ) );
			byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
			for (int i = 0; i < data.length; i++) {
				classifyPixel(data[i],histogram);
			}
			/*width = bi.getWidth();
			height = bi.getHeight();
			for (int w = 0; w < width/10; w++) {
				for (int h = 0; h < height/10; h++) {
					classifyPixel(bi.getRGB(w, h),histogram);	
				}
			}*/
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return histogram;
	}


	private void classifyPixel(int pixel, double[] histogram) {
		double tmpResult = 0;
		tmpResult += (pixel & mask); //blue
		tmpResult += ((pixel >> 8) & mask); //green
		tmpResult += ((pixel >> 16) & mask); //red
		tmpResult /= 3;
		for (int i = 0; i < N; i++) {
			if (tmpResult <= i*rank) {
				histogram[i]++;
				return;
			}
		}
	}
}
